package org.ourgrid.broker.ui.async.gui.graphical.actions;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import org.ourgrid.broker.ui.async.client.BrokerAsyncInitializer;
import org.ourgrid.common.spec.main.CompilerException;
import org.ourgrid.gridMonitor.BrokerProperties;
import org.ourgrid.gridMonitor.operations.BrokerLocalOperation;

public class JobsListManager {

private static int jobId = 0;	
private static String filename = "jobsList" + new BrokerProperties().getXMPPUsername().toUpperCase();
	
	public static void saveJobsList(String jobPath){
		try {
			//Insere o job na lista desse usuário
			System.out.println("Inserindo job na lista de jobs");
			PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(filename,true)));
			
			jobId++;
			Date date = new Date();
			
			String job = filename+"#"+jobId+"#"+date.getTime()+"#"+jobPath; 
			
			pw.println(job);
			pw.close();
			
			BrokerLocalOperation.sendNewJob(job);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	public static void cleanJobsList(){
		try {
			System.out.println("Limpando lista de jobs");
			RandomAccessFile raf = new RandomAccessFile(new File(filename), "rw");
			raf.setLength(0);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void removeJobsFromList(String path){
		try {
			System.out.println("Removendo job da lista de jobs");
			RandomAccessFile raf = new RandomAccessFile(new File(filename), "rw");
			
			int contador = 0;
			while(raf.readLine() != null){
				contador++;
			}
			//volta para o inÃ­cio do arquivo
			raf.seek(0);
			
			
			Collection<String> lista = new ArrayList<String>();
			
			int i = 0;
			while(i < contador){
				String linha = raf.readLine();
				if(!linha.equals(path)){
					lista.add(linha);
				}
				i++;
			}
			
			for (String job : lista) {
				saveJobsList(job);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String args[]){
		removeJobsFromList("");
	}
	
	public static void recoveryJobsList(){
		try{
		RandomAccessFile raf = new RandomAccessFile(new File(filename), "rw");
		
		int contador = 0;
		while(raf.readLine() != null){
			contador++;
		}
		//volta para o inÃ­cio do arquivo
		raf.seek(0);
		
		
		Collection<String> lista = new ArrayList<String>();
		System.out.println("Recuperando os jobs...");
		int i = 0;
		while(i < contador){
			String linha = raf.readLine();
			String valores[] = linha.split("#");
			
			BrokerAsyncInitializer.getInstance().getComponentClient().addJob(valores[2], true);	
			i++;
		}
		System.out.println("RecuperaÃ§Ã£o concluÃ­da.");
		}catch(IOException e){
			e.printStackTrace();
		} catch (CompilerException e) {
			e.printStackTrace();
		} 
	}
	
}
